package com.czy.owner.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.SelectBespokeAdapter;
import com.czy.owner.adapter.SelectBespokeTabAdapter;
import com.czy.owner.api.OrderSelectBespokeSelectApi;
import com.czy.owner.api.OrderSerchLeatlyApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.BaseCurrencyListModel;
import com.czy.owner.entity.OderSerchLeatlyListModel;
import com.czy.owner.entity.OrdersListModel;
import com.czy.owner.entity.SelectBespokeListModel;
import com.czy.owner.entity.WebViewRequestParam;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.KeyboardUtils;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.StringUtils;
import com.easyrecycleview.EasyRecycleViewUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.easyrecycleview.decoration.SpaceDecoration;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.czy.owner.entity.WebViewRequestParam.REQUEST_POST;
import static com.czy.owner.ui.store.OnLineOrderActivity2.REQUEST_DATA;

/**
 * Created by hedepu on 2017-08-25
 */

public class SelectSearchBespokeActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnLoadMoreListener {
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.recyler_select)
    EasyRecyclerView recylerSelect;
    SelectBespokeTabAdapter selectBespokeAdapter;
    @BindView(R.id.recyler_seletc_tab)
    RecyclerView recylerSeletcTab;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    private List<OderSerchLeatlyListModel> list = new ArrayList<>();
    private SelectBespokeAdapter adapter;
    private int page = 1;
    private Handler handler = new Handler();
    private String session = "";
    private List<SelectBespokeListModel> dataList = new ArrayList<>();
    private String ServiceName;
    private List<SelectBespokeListModel> bespokelist = new ArrayList<>();
    private String serchName;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_select_search_bespoke;
    }

    @Override
    protected void initInjector() {


    }

    @Override
    protected void initViews() {

        if (getIntent().getSerializableExtra("bespoke") != null)
            bespokelist = (List<SelectBespokeListModel>) getIntent().getSerializableExtra("bespoke");
        toolbarTitle.setText("搜索");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setTitle("");
        session = UserHelper.getInstance().getSessionInfoModel(this).getSession();
        recylerSelect.setLayoutManager(new LinearLayoutManager(this));
        recylerSelect.setAdapterWithProgress(adapter = new SelectBespokeAdapter(this));
//        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_order_fragment_recyclerview_divider_decoration));
        recylerSelect.setEmptyView(R.layout.order_empty_view);
        recylerSelect.setErrorView(R.layout.view_error_refresh);
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore);
        adapter.setSelectedList(bespokelist);
        adapter.addAll(dataList);
//        adapter.setError(R.layout.view_error_click).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                adapter.resumeMore();
//            }
//        });
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<SelectBespokeListModel>() {
            @Override
            public void onItemClick(View view, int position, SelectBespokeListModel model) {
                WebViewRequestParam webViewRequestParam = new WebViewRequestParam(Constants.APP_API_BASE + "/own/order/serviceInfo");
                webViewRequestParam.setRequestMethod(REQUEST_POST);
                webViewRequestParam.setParams("session=" + UserHelper.getInstance().getSessionInfoModel(SelectSearchBespokeActivity.this).getSession() + "&storeId=" + (SharedPreferencesUtils.getParam(SelectSearchBespokeActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "") + "&storeServiceId="
                        + model.getStoreServiceId());
                webViewRequestParam.setTitle("服务详情");
                Intent intent = new Intent(SelectSearchBespokeActivity.this, ProjectDetailsWebviewActivity.class);
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, webViewRequestParam);
                startActivity(intent);


            }
        });
        recylerSelect.setRefreshListener(this);
        recylerSelect.setEmptyView(R.layout.view_empty_common);
        recylerSelect.showEmpty();
        getLeatlyList();
    }

    //获取项目服务
    private void getDataList(final boolean isFirst) {
        OrderSelectBespokeSelectApi orderListApi = new OrderSelectBespokeSelectApi(new HttpOnNextListener<BaseCurrencyListModel<SelectBespokeListModel>>() {
            @Override
            public void onNext(BaseCurrencyListModel<SelectBespokeListModel> model) {
                if (isFirst)
                    adapter.clear();
                setDataList(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<OrdersListModel>>() {
                }.getType();
                BaseResultEntity<OrdersListModel> model = gson.fromJson(cache, type);

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(SelectSearchBespokeActivity.this, e.getMessage());
            }


        }, SelectSearchBespokeActivity.this);
        orderListApi.setSession(UserHelper.getInstance().getSessionInfoModel(SelectSearchBespokeActivity.this).getSession());
        orderListApi.setStoreId(SharedPreferencesUtils.getParam(SelectSearchBespokeActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        orderListApi.setPage(page + "");
        orderListApi.setServiceName(ServiceName);
        orderListApi.setSize("50");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(orderListApi);
    }

    //填充数据
    private void setDataList(BaseCurrencyListModel<SelectBespokeListModel> model) {
        if (model.getList().size() < 9) {
            adapter.stopMore();
        }
        adapter.addAll(model.getList());
        if (adapter.getAllData().size() == 0) {
//            recylerSelect.setEmptyView(R.layout.view_empty_common);
            recylerSelect.showEmpty();
        }
    }

    //获取项目服务
    private void getLeatlyList() {
        OrderSerchLeatlyApi orderSerchLeatlyApi = new OrderSerchLeatlyApi(new HttpOnNextListener<BaseResultEntity<List<OderSerchLeatlyListModel>>>() {
            @Override
            public void onNext(BaseResultEntity<List<OderSerchLeatlyListModel>> model) {
                PhoneUtils.ShowToastMessage(SelectSearchBespokeActivity.this, model.getData().size() + "");
                list.addAll(model.getData());

                setTabData();
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<List<OderSerchLeatlyListModel>>>() {
                }.getType();
                BaseResultEntity<List<OderSerchLeatlyListModel>> model = gson.fromJson(cache, type);
                list.addAll(model.getData());
                setTabData();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(SelectSearchBespokeActivity.this, e.getMessage());
            }


        }, this);
        orderSerchLeatlyApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        orderSerchLeatlyApi.setStoreId(SharedPreferencesUtils.getParam(this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        orderSerchLeatlyApi.setSize("8");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(orderSerchLeatlyApi);
    }

    public void setTabData() {
        selectBespokeAdapter = new SelectBespokeTabAdapter(SelectSearchBespokeActivity.this, list);
        recylerSeletcTab.setAdapter(selectBespokeAdapter);
        recylerSeletcTab.setLayoutManager(new GridLayoutManager(SelectSearchBespokeActivity.this, 3));
        SpaceDecoration itemDecoration = new SpaceDecoration((int) EasyRecycleViewUtils.convertDpToPixel(8, SelectSearchBespokeActivity.this));
        itemDecoration.setPaddingEdgeSide(true);
        itemDecoration.setPaddingStart(true);
        recylerSeletcTab.addItemDecoration(itemDecoration);
        selectBespokeAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object o, View view) {
                serchName = StringUtils.getString(list.get(position).getServiceName(), "");
                selectBespokeAdapter.setIsPostin(position + "");
                etSearch.setText(StringUtils.getString(list.get(position).getServiceName(), ""));
                ServiceName = StringUtils.getString(list.get(position).getServiceName(), "");
                if (!StringUtils.isEmpty(ServiceName)) {
                    etSearch.setSelection(ServiceName.length());//将光标移至文字末尾
                }
                onRefresh();
            }
        });
    }

    @Override
    protected void updateViews() {


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            Intent intent = new Intent();
            intent.putExtra("bespoke", (Serializable) adapter.getSelectedList());
            setResult(REQUEST_DATA, intent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("bespoke", (Serializable) adapter.getSelectedList());
            setResult(REQUEST_DATA, intent);
            finish();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(SelectSearchBespokeActivity.this)) {
                    adapter.pauseMore();
                    recylerSelect.showError();
                    return;
                }
                page++;
                getDataList(false);

            }
        }, 1000);
    }


    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(SelectSearchBespokeActivity.this)) {
                    adapter.pauseMore();
                    recylerSelect.showError();
                    return;
                }
                page = 1;
                getDataList(true);
            }
        }, 1000);
    }


    @OnClick({R.id.img_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.img_search:
                if (etSearch.getText().toString().isEmpty()) {
                    PhoneUtils.ShowToastMessage(this, "你还未输入搜索的内容");
                    return;
                }
                ServiceName = etSearch.getText().toString();
                if (selectBespokeAdapter != null && selectBespokeAdapter.getIsPostin() != null && !selectBespokeAdapter.getIsPostin().isEmpty() && !ServiceName.equals(list.get(Integer.parseInt(selectBespokeAdapter.getIsPostin())).getServiceName())) {
                    selectBespokeAdapter.setIsPostin("");
                }

                KeyboardUtils.hideSoftInput(this);
                onRefresh();
                break;
        }
    }
}
